<?php

namespace App\Events;

use App\Models\User\User;
use App\Trip\Train\TrainQueryFromToData;
use Exception;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;

class TripQueryNotifyEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public array $trip;

    /**
     * Create a new event instance.
     *
     * @return void
     * @throws Exception
     */
    public function __construct(User $user, array $trip_data)
    {
        /**
         * @var TrainQueryFromToData $to
         */
        $to = $trip_data['to'] ?? null;
        if (!$to) {
            return;
        }

        $city              = $to->parse2City();
        $tail_phone_number = tail_phone_number($user->getPhone());
        if (!$tail_phone_number) {
            return;
        }
        $this->trip = [
            'user_info'  => [
                'avatar'            => $user->getAvatar(),
                'nickname'          => $user->getNickName(),
                'tail_phone_number' => $tail_phone_number,
            ],
            'trip_type'  => $trip_data['trip_type'],
            //            'to'         => [
            //                'name'    => $city['name'],
            //                'name_uy' => $city['name_uy'],
            //            ],
            'message'    => "尾号{$tail_phone_number}正在计划前往[{$city['name']}]",
            'message_uy' => Str::replace(['city', 6080], [$city['name_uy'], $tail_phone_number], " ئاخىرقى نومۇرى 6080 ［city］غا بېرىشنى پىلانلىدى. "),
            'action'     => $trip_data['action'],
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel("trip.query");
    }

    public function broadcastAs()
    {
        return 'trip.query';
    }

    /**
     * 判定事件是否广播
     *
     * 如果只想 广播 已支付 已取消等 可以加逻辑
     *
     * @return bool
     */
    public function broadcastWhen()
    {
        return true;
    }
}
